<template>
  <div>
    <div id="root">
      <div class="todo-container">
        <div class="todo-wrap">
          <Header :addData="addData" />
          <!-- 将数据传过去 加：是提供差值 查变量 -->
          <List
            :todos="todos"
            :deleteData="deleteData"
            :singleCheckHandle="singleCheckHandle"
          />
          <Footer
            :todos="todos"
            :allComplete="allComplete"
            :killComplete="killComplete"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { v4 as uuidv4 } from "uuid";

import Header from "./components/Header";
import List from "./components/List";
import Footer from "./components/Footer";

export default {
  name: "App",
  components: { Header, List, Footer },
  data() {
    return {
      todos: [
        // { id: uuidv4(), title: "抽烟", done: false },
        // { id: uuidv4(), title: "喝酒", done: false },
        // { id: uuidv4(), title: "烫头", done: false },
      ],
    };
  },

  methods: {
    //增加数据
    addData(newData) {
      this.todos.unshift(newData);
    },
    //单个勾选
    singleCheckHandle(id) {
      //这种写法不推荐，因为修改数组的数据有两种 1.使用vue包裹之后的变更方法 2.重新对变量赋值
      /* this.todoList.forEach((item) => {
        item.done = item.id === id ? !item.done : item.done;
      }); */

      //修改数组中对象的值
      this.todos = this.todos.map((item) => {
        return item.id === id ? { ...item, done: !item.done } : item;
      });
    },
    //删除数据
    deleteData(id) {
      let tp =  confirm("确定删除？")
      if(!tp) return 
      this.todos = this.todos.filter((item) => {
        return item.id !== id;
      });
    },
    //已完成
    allComplete(value) {
      this.todos = this.todos.map((item) => {
        return { ...item, done: value };
      });
    },
    //清除以完成
    killComplete() {
      this.todos = this.todos.filter((item) => {
        return item.done !== true;
      });
    },
  },
  //数据持久化
  mounted() {
    this.todos = JSON.parse(localStorage.getItem("todos") || "[]");
  },
  watch: {
    todos: {
      deep: true,
      handler() {
        localStorage.setItem("todos", JSON.stringify(this.todos));
      },
    },
  },
};
</script>

<style>
/*base*/
body {
  background: #fff;
}
.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>